package xin.nick.minicat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Nick
 * @date 2021/6/20
 * @description
 */
public class StaticResourceUtil {


    /**
     * 读取绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {

        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return new StringBuilder(absolutePath.replaceAll("\\\\", "/"))
                .append(path).toString();

    }

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        long writLen = 0;
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (writLen < resourceSize) {
            // 当剩余未读取的大小不足一kb时,将真实长度放进去
            if (writLen + byteSize > resourceSize) {
                // 剩余真实长度
                byteSize = (int) (resourceSize - writLen);
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            writLen += byteSize;

        }

    }

}
